package biz.yfsoft.app.fastframework.plugin.quartz;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import org.quartz.CronScheduleBuilder;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;

import biz.yfsoft.app.fastframework.plugin.BaseFastPlugin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * 默认的任务调度插件
 * @author YFsoft
 *
 */
public class DefaultQuartzPlugin extends BaseFastPlugin{

	
	private Scheduler sched = null;
	
	public DefaultQuartzPlugin(){
		
	}
	
	@Override
	public boolean start() {
		//读取到配置文件中的所有任务和触发器属性
		String jobs = properties.getProperty("jobs");
		if(jobs == null){
			//未进行任务调度的配置
			status = Status.ACTIVED;
			return true;
		}
		JSONArray jobsJsonArray = JSONArray.parseArray(jobs);
		int len = jobsJsonArray.size();
		if(len<0){
			//没有读取到任何任务清单，直接返回
			status = Status.ACTIVED;
			return true;
		}
		
		//创建一个全局的调度器
		SchedulerFactory sf = new StdSchedulerFactory();      
		
        try {
			sched = sf.getScheduler();
		} catch (SchedulerException e) {
			e.printStackTrace();
			//创建调度器失败
			status = Status.EXCEPTION;
			return false;
		}
        
		for(int i = 0 ; i<len ; i++){
			JSONObject jobObj = jobsJsonArray.getJSONObject(i);
			String clz = jobObj.getString("class");
			String id = jobObj.getString("id");
			String group = jobObj.getString("group");
			String triggerId = jobObj.getString("trigger");
			String cron = jobObj.getString("cron");
			//
			Class<?> jobClz = null;
			try {
				jobClz = Class.forName(clz);
			} catch (ClassNotFoundException e1) {
				e1.printStackTrace();
			}
			Job j = null;
			try {
				j = (Job)jobClz.newInstance();
			} catch (InstantiationException | IllegalAccessException e1) {
				e1.printStackTrace();
			}
			JobDetail job = newJob(j.getClass()).withIdentity(id, group).build();
			Trigger trigger = newTrigger().withIdentity(triggerId, group)
	        		.withSchedule(CronScheduleBuilder.cronSchedule(cron)).build();  
	  
	        // 注册并进行调度  
	        try {
				sched.scheduleJob(job, trigger);
			} catch (SchedulerException e) {
				//注册调度任务失败
			}  
		}
		
		// 启动调度器  
        try {
			sched.start();
		} catch (SchedulerException e) {
			e.printStackTrace();
			//启动失败
			status = Status.EXCEPTION;
			return false;
		} 
        status = Status.ACTIVED;
		return true;
	}

	@Override
	public boolean stop() {
		if(sched!=null)
			try {
				sched.shutdown(true);
			} catch (SchedulerException e) {
				e.printStackTrace();
			}
		super.stop();
		return true;
	}

}
